package com.atguigu.service.impl;

import com.atguigu.base.BaseMapper;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.entity.AclRole;
import com.atguigu.entity.RolePermission;
import com.atguigu.mapper.AdminRoleMapper;
import com.atguigu.mapper.RoleMapper;
import com.atguigu.mapper.RolePermissionMapper;
import com.atguigu.service.RoleService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class RoleServiceImpl extends BaseServiceImpl<AclRole> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public BaseMapper<AclRole> getBaseMapper() {
        return roleMapper;
    }

    @Override
    public Map<String, Object> findRoleListByAdminId(Long id) {
        //所有角色
        List<AclRole> roleList = roleMapper.findAll();
        //已经分配的角色Id
        List<Long> assignRoleIdList = adminRoleMapper.findRoleIdListByAdminId(id);
        //未分配到的角色
        List<AclRole> assignRoleList = new ArrayList<>();
        List<AclRole> unAssignRoleList = new ArrayList<>();

        for (AclRole role : roleList) {
            if(assignRoleIdList.contains(role.getId())){
                assignRoleList.add(role);
            }else {
                unAssignRoleList.add(role);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("assignRoleList",assignRoleList);
        map.put("unAssignRoleList",unAssignRoleList);
        return map;
    }

    @Override
    public void assignPermission(Long roleId, Long[] permissionIds) {
        //删除之前的权限
        rolePermissionMapper.deleteByRoleId(roleId);
        //添加新的权限
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionMapper.insert(rolePermission);
        }
    }
}